import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { AfMessageService } from '@core';
import { _HttpClient } from '@delon/theme';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { BehaviorSubject, Observable, of, zip } from 'rxjs';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';

import { CodeGenService } from '../../codegen.service';
import { LangService } from '../../lang/lang.service';

@Component({
  selector: 'app-data-source-select',
  templateUrl: './data-source-select.component.html'
})
export class DataSourceSelectComponent implements OnInit {
  selectedTable: any = undefined;
  dbSources: any[] | null = null;
  dbSourceName: any = undefined;
  optionList: any[] = [];

  dbSourceOptions: any[] | null = [
    {
      value: 'mysql',
      label: 'mysql',
      children: [
        {
          value: 'ms-code-generator',
          label: 'ms-code-generator',
          isLeaf: true
        }
      ]
    },
    {
      value: 'oracle',
      label: 'oracle',
      children: [
        {
          value: 'or-dev-test',
          label: 'or-dev-test',
          isLeaf: true
        }
      ]
    }
  ];

  constructor(
    private modalRef: NzModalRef,
    private http: _HttpClient,
    private codegen: CodeGenService,
    private cdr: ChangeDetectorRef,
    private msgSrv: AfMessageService,
    private langServ: LangService
  ) {}

  ngOnInit(): void {
    this.queryDataSource();
  }

  isLoading = false;
  public queryDataSource() {
    this.isLoading = true;
    this.cdr.detectChanges();
    this.codegen.getDataSourceCascader().subscribe(body => {
      this.isLoading = false;
      if (body.status) {
        this.dbSourceOptions = body.data;
        console.log(JSON.stringify(this.dbSourceOptions));
      } else {
        this.msgSrv.notice_warning('查询数据源', `警告编号${body.code};  警告信息${body.msg}`);
      }
    });
  }

  searchChange$ = new BehaviorSubject('');
  // 通过searchChange，来触发执行查询表列表
  onTableSearch(value: string): void {
    this.isLoading = true;
    this.searchChange$.next(value);
  }

  target_dbType: any;
  // 通过选择数据源，来设置searchChange事件
  onCascaderChanges(values: any): void {
    console.log(values);
    if (values != undefined && values != null) {
      this.dbSourceName = values![1];
      this.target_dbType = values![0];
      this.setOptionListEvent();
    }
  }
  public setOptionListEvent() {
    if (this.dbSourceName == undefined || this.dbSourceName == '') {
      return;
    }

    const getRandomNameList = (name: string): Observable<any> =>
      this.http.get(this.langServ.getTableListUrl(this.dbSourceName, name)).pipe(
        catchError(() => of({ data: [] })),
        map((res: any) => res.data)
      );
    const optionList$: Observable<string[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(getRandomNameList));
    optionList$.subscribe(data => {
      this.optionList = data;
      this.cdr.detectChanges();
      this.isLoading = false;
    });
  }

  close() {
    this.modalRef.destroy({ status: false });
  }

  submit() {
    if (this.selectedTable && this.selectedTable !== '') {
      const value = {
        selectedTable: this.selectedTable,
        dbSources: this.dbSources,
        selectedDataSource: this.dbSourceName
      };
      this.modalRef.close({ status: true, data: value });
    } else {
      this.msgSrv.msg_warning('请选择一个表');
    }
  }
}
